#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <assert.h>


void usage();
int main(int argc,char **argv)
{
	if(argc != 3)
	{
		usage();
		exit(1);
	}
	unsigned long long tail,total_item_num,read_num,size;
	char *db = argv[1];
	struct stat st;
	stat(db,&st);
	int fd=open(db,O_RDONLY);
	if( fd <= 0)
	{
		perror("open");
		exit(3);
	}
	void *m=mmap(0,st.st_size,PROT_READ,MAP_SHARED,fd,0);
	if(m == MAP_FAILED)
	{
		perror("mmap");
		exit(2);
	}
	read_num=strtoull(argv[2],(char **)NULL,10);
	memcpy(&total_item_num,m+2*sizeof(long long),sizeof(long long));
	memcpy(&tail,m+sizeof(long long),sizeof(long long));
	if(read_num > total_item_num) read_num=total_item_num;
	void *buf=calloc(8192,1);
	for(;read_num > 0;read_num--)
	{
		memcpy(&size,m+tail,sizeof(int));
		tail+=3*sizeof(int);
		memcpy(buf,m+tail,size-2);
		tail+=size;
		printf("%s\n",(char *)buf);
		memset(buf,0,sizeof(buf));
	}
	free(buf);
	return 0;
}
void usage()
{
	fprintf(stderr,"dump db_file_name num_to_dump\n");
	fprintf(stderr,"for example:\n");
	fprintf(stderr,"dump test.db 10\n");
}
